<template>
  <div class="app-container">
    <el-card class="survey-design">
      <div slot="header">
        <span>问卷设计</span>
        <div style="float: right;">
          <el-button type="primary" @click="saveSurvey">保存</el-button>
          <el-button type="success" @click="publishSurvey">发布</el-button>
          <el-button @click="previewSurvey">预览</el-button>
          <el-button @click="goBack">返回</el-button>
        </div>
      </div>
      
      <el-row :gutter="20">
        <!-- 问卷编辑区 -->
        <el-col :span="16">
          <div class="edit-area">
            <!-- 问卷标题和说明 -->
            <div class="survey-header">
              <el-input
                v-model="survey.title"
                placeholder="请输入问卷标题"
                class="title-input"
              ></el-input>
              <el-input
                v-model="survey.description"
                type="textarea"
                :rows="3"
                placeholder="请输入问卷说明文字"
                class="desc-input"
              ></el-input>
              <div class="survey-settings">
                <el-form :inline="true" size="small">
                  <el-form-item label="截止时间">
                    <el-date-picker
                      v-model="survey.endTime"
                      type="datetime"
                      placeholder="选择截止时间"
                      value-format="yyyy-MM-dd HH:mm:ss"
                    ></el-date-picker>
                  </el-form-item>
                </el-form>
              </div>
            </div>
            
            <!-- 问题列表 -->
            <div class="questions-container">
              <el-collapse v-model="activeNames">
                <draggable v-model="survey.questions" handle=".drag-handle" @start="drag=true" @end="drag=false">
                  <el-collapse-item
                    v-for="(question, index) in survey.questions"
                    :key="index"
                    :name="index"
                  >
                    <template slot="title">
                      <div class="question-header">
                        <i class="el-icon-s-operation drag-handle"></i>
                        <span class="question-title">{{ index + 1 }}. {{ question.title || '未命名问题' }}</span>
                        <span class="question-type">{{ getQuestionTypeName(question.type) }}</span>
                        <el-tag v-if="question.required" size="mini" type="danger">必填</el-tag>
                      </div>
                    </template>
                    
                    <div class="question-edit">
                      <el-form label-position="top" :model="question">
                        <el-form-item label="问题标题">
                          <el-input v-model="question.title" placeholder="请输入问题"></el-input>
                        </el-form-item>
                        
                        <el-form-item label="问题类型">
                          <el-select v-model="question.type" placeholder="请选择问题类型" @change="handleTypeChange(index)">
                            <el-option label="单选题" value="radio"></el-option>
                            <el-option label="多选题" value="checkbox"></el-option>
                            <el-option label="填空题" value="text"></el-option>
                            <el-option label="评分题" value="rate"></el-option>
                          </el-select>
                        </el-form-item>
                        
                        <!-- 单选题或多选题的选项 -->
                        <template v-if="question.type === 'radio' || question.type === 'checkbox'">
                          <el-form-item label="选项">
                            <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                              <el-input v-model="option.label" placeholder="请输入选项">
                                <template slot="prepend">{{ optIndex + 1 }}</template>
                                <el-button slot="append" icon="el-icon-delete" @click="removeOption(index, optIndex)"></el-button>
                              </el-input>
                            </div>
                            <div class="add-option">
                              <el-button type="text" icon="el-icon-plus" @click="addOption(index)">添加选项</el-button>
                            </div>
                          </el-form-item>
                        </template>
                        
                        <!-- 评分题设置 -->
                        <template v-if="question.type === 'rate'">
                          <el-form-item label="评分等级">
                            <el-slider
                              v-model="question.max"
                              :min="3"
                              :max="10"
                              :marks="{3:'3分', 5:'5分', 10:'10分'}"
                              show-stops
                            ></el-slider>
                          </el-form-item>
                        </template>
                        
                        <!-- 填空题设置 -->
                        <template v-if="question.type === 'text'">
                          <el-form-item label="输入框行数">
                            <el-input-number v-model="question.rows" :min="1" :max="10"></el-input-number>
                          </el-form-item>
                          <el-form-item label="占位文本">
                            <el-input v-model="question.placeholder" placeholder="请输入占位文本"></el-input>
                          </el-form-item>
                        </template>
                        
                        <el-form-item>
                          <el-checkbox v-model="question.required">此题必填</el-checkbox>
                        </el-form-item>
                        
                        <div class="question-actions">
                          <el-button type="text" icon="el-icon-copy-document" @click="copyQuestion(index)">复制</el-button>
                          <el-button type="text" icon="el-icon-delete" @click="removeQuestion(index)">删除</el-button>
                        </div>
                      </el-form>
                    </div>
                  </el-collapse-item>
                </draggable>
              </el-collapse>
              
              <!-- 添加新问题 -->
              <div class="add-question">
                <el-dropdown split-button type="primary" @command="addQuestion">
                  添加问题
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="radio">单选题</el-dropdown-item>
                    <el-dropdown-item command="checkbox">多选题</el-dropdown-item>
                    <el-dropdown-item command="text">填空题</el-dropdown-item>
                    <el-dropdown-item command="rate">评分题</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
          </div>
        </el-col>
        
        <!-- 问卷设置区 -->
        <el-col :span="8">
          <div class="settings-area">
            <el-card shadow="never">
              <div slot="header">
                <span>问卷设置</span>
              </div>
              
              <el-form label-width="100px" size="small">
                <el-form-item label="问卷状态">
                  <el-tag v-if="survey.status === '0'" type="info">未发布</el-tag>
                  <el-tag v-else-if="survey.status === '1'" type="success">进行中</el-tag>
                  <el-tag v-else-if="survey.status === '2'" type="warning">已结束</el-tag>
                  <el-tag v-else type="danger">已归档</el-tag>
                </el-form-item>
                
                <el-form-item label="创建时间">
                  <span>{{ survey.createTime }}</span>
                </el-form-item>
                
                <el-form-item label="截止时间">
                  <el-date-picker
                    v-model="survey.endTime"
                    type="datetime"
                    placeholder="选择截止时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 100%;"
                  ></el-date-picker>
                </el-form-item>
                
                <el-form-item label="是否匿名">
                  <el-switch v-model="survey.anonymous"></el-switch>
                </el-form-item>
                
                <el-form-item label="提交后显示">
                  <el-checkbox v-model="survey.showResult">显示统计结果</el-checkbox>
                </el-form-item>
                
                <el-form-item label="提示语">
                  <el-input
                    v-model="survey.submitTip"
                    type="textarea"
                    :rows="2"
                    placeholder="提交问卷后的提示语"
                  ></el-input>
                </el-form-item>
              </el-form>
            </el-card>
            
            <el-card shadow="never" style="margin-top: 20px;">
              <div slot="header">
                <span>问题模板</span>
              </div>
              
              <div class="template-list">
                <div v-for="(template, index) in questionTemplates" :key="index" class="template-item" @click="useTemplate(template)">
                  <div class="template-icon">
                    <i :class="template.icon"></i>
                  </div>
                  <div class="template-info">
                    <div class="template-title">{{ template.title }}</div>
                    <div class="template-desc">{{ template.description }}</div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 预览对话框 -->
    <el-dialog title="问卷预览" :visible.sync="previewVisible" width="800px" top="5vh" :before-close="closePreview">
      <div class="preview-container">
        <div class="preview-header">
          <h2 class="preview-title">{{ survey.title }}</h2>
          <p class="preview-description">{{ survey.description }}</p>
        </div>
        
        <div class="preview-body">
          <div v-for="(question, index) in survey.questions" :key="index" class="preview-question">
            <div class="question-title">
              <span class="question-index">{{ index + 1 }}.</span>
              <span class="question-text">{{ question.title }}</span>
              <span v-if="question.required" class="question-required">*</span>
            </div>
            
            <!-- 单选题预览 -->
            <div v-if="question.type === 'radio'" class="question-options">
              <el-radio-group v-model="previewAnswers[index]">
                <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                  <el-radio :label="option.value">{{ option.label }}</el-radio>
                </div>
              </el-radio-group>
            </div>
            
            <!-- 多选题预览 -->
            <div v-else-if="question.type === 'checkbox'" class="question-options">
              <el-checkbox-group v-model="previewAnswers[index]">
                <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                  <el-checkbox :label="option.value">{{ option.label }}</el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
            
            <!-- 填空题预览 -->
            <div v-else-if="question.type === 'text'" class="question-options">
              <el-input
                v-model="previewAnswers[index]"
                type="textarea"
                :rows="question.rows || 3"
                :placeholder="question.placeholder || '请输入您的答案'"
              ></el-input>
            </div>
            
            <!-- 评分题预览 -->
            <div v-else-if="question.type === 'rate'" class="question-options">
              <el-rate
                v-model="previewAnswers[index]"
                :max="question.max || 5"
                show-text
                :texts="['很差', '较差', '一般', '较好', '很好']"
              ></el-rate>
            </div>
          </div>
        </div>
        
        <div class="preview-footer">
          <el-button type="primary">提交问卷</el-button>
          <el-button @click="resetPreview">重置</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import draggable from 'vuedraggable';

export default {
  name: "SurveyDesign",
  components: {
    draggable
  },
  data() {
    return {
      surveyId: null,
      survey: {
        id: undefined,
        title: "新建问卷",
        description: "请填写问卷说明文字",
        status: "0", // 0-未发布，1-进行中，2-已结束，3-已归档
        createTime: this.formatDate(new Date()),
        endTime: this.formatDate(new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000)), // 默认一周后截止
        anonymous: true, // 是否匿名
        showResult: false, // 提交后是否显示结果
        submitTip: "感谢您的参与，问卷已提交成功！", // 提交后的提示语
        questions: []
      },
      activeNames: [], // 当前展开的问题索引
      drag: false, // 是否正在拖拽
      previewVisible: false, // 预览对话框
      previewAnswers: [], // 预览答案
      questionTemplates: [
        {
          title: "满意度调查",
          description: "评估满意度的常用问题",
          icon: "el-icon-s-opportunity",
          questions: [
            {
              title: "您对我们的服务总体满意度如何？",
              type: "radio",
              required: true,
              options: [
                { label: "非常满意", value: "5" },
                { label: "比较满意", value: "4" },
                { label: "一般", value: "3" },
                { label: "不太满意", value: "2" },
                { label: "非常不满意", value: "1" }
              ]
            },
            {
              title: "您认为我们需要改进的方面有哪些？（多选）",
              type: "checkbox",
              required: false,
              options: [
                { label: "服务态度", value: "attitude" },
                { label: "服务质量", value: "quality" },
                { label: "响应速度", value: "speed" },
                { label: "价格", value: "price" },
                { label: "其他", value: "other" }
              ]
            },
            {
              title: "您对我们的建议和意见",
              type: "text",
              required: false,
              rows: 3,
              placeholder: "请输入您的宝贵建议"
            }
          ]
        },
        {
          title: "活动报名",
          description: "活动报名表单模板",
          icon: "el-icon-s-flag",
          questions: [
            {
              title: "您的姓名",
              type: "text",
              required: true,
              rows: 1,
              placeholder: "请输入您的姓名"
            },
            {
              title: "您的联系方式",
              type: "text",
              required: true,
              rows: 1,
              placeholder: "请输入您的手机号码"
            },
            {
              title: "您希望参加的活动类型",
              type: "checkbox",
              required: true,
              options: [
                { label: "户外拓展", value: "outdoor" },
                { label: "文化沙龙", value: "salon" },
                { label: "体育赛事", value: "sports" },
                { label: "志愿服务", value: "volunteer" }
              ]
            }
          ]
        },
        {
          title: "培训需求",
          description: "培训需求调研模板",
          icon: "el-icon-s-management",
          questions: [
            {
              title: "您最感兴趣的培训主题是？",
              type: "radio",
              required: true,
              options: [
                { label: "专业技能", value: "skills" },
                { label: "管理能力", value: "management" },
                { label: "团队协作", value: "teamwork" },
                { label: "职业发展", value: "career" }
              ]
            },
            {
              title: "您期望的培训形式是？",
              type: "radio",
              required: true,
              options: [
                { label: "线下课程", value: "offline" },
                { label: "线上直播", value: "live" },
                { label: "视频录播", value: "video" },
                { label: "实践工作坊", value: "workshop" }
              ]
            },
            {
              title: "您对培训的其他需求和建议",
              type: "text",
              required: false,
              rows: 3,
              placeholder: "请输入您的需求和建议"
            }
          ]
        }
      ]
    };
  },
  created() {
    this.surveyId = this.$route.params.id;
    // 如果是编辑模式，则获取问卷数据
    if (this.surveyId) {
      this.loadSurveyData();
    } else {
      // 新建模式，添加默认问题
      this.addQuestion("radio");
    }
  },
  methods: {
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:00`;
    },
    
    // 加载问卷数据
    loadSurveyData() {
      // 这里应该调用后端接口，暂时使用模拟数据
      setTimeout(() => {
        this.survey = {
          id: this.surveyId,
          title: "员工满意度调查问卷",
          description: "为了更好地了解员工对公司各方面的满意度，提升公司管理和服务水平，特开展本次调查。您的意见对我们非常重要，感谢您的参与！",
          status: "0",
          createTime: "2023-03-01 10:00:00",
          endTime: "2023-03-15 23:59:59",
          anonymous: true,
          showResult: false,
          submitTip: "感谢您的参与，问卷已提交成功！",
          questions: [
            {
              title: "您对公司工作环境的满意度是？",
              type: "radio",
              required: true,
              options: [
                { label: "非常满意", value: "5" },
                { label: "比较满意", value: "4" },
                { label: "一般", value: "3" },
                { label: "不太满意", value: "2" },
                { label: "非常不满意", value: "1" }
              ]
            },
            {
              title: "您认为公司需要改善的方面有哪些？（多选）",
              type: "checkbox",
              required: true,
              options: [
                { label: "工作环境", value: "environment" },
                { label: "薪资福利", value: "salary" },
                { label: "培训发展", value: "training" },
                { label: "团队氛围", value: "team" },
                { label: "管理制度", value: "management" },
                { label: "其他", value: "other" }
              ]
            },
            {
              title: "请对公司的管理制度进行评分",
              type: "rate",
              required: true,
              max: 5
            },
            {
              title: "请描述您对公司未来发展的建议",
              type: "text",
              required: false,
              rows: 3,
              placeholder: "请输入您的建议"
            }
          ]
        };
        // 默认展开第一个问题
        this.activeNames = [0];
      }, 500);
    },
    
    // 返回列表
    goBack() {
      this.$router.push("/system/survey");
    },
    
    // 获取问题类型名称
    getQuestionTypeName(type) {
      const typeMap = {
        'radio': '单选题',
        'checkbox': '多选题',
        'text': '填空题',
        'rate': '评分题'
      };
      return typeMap[type] || '未知类型';
    },
    
    // 添加问题
    addQuestion(type) {
      let newQuestion = {
        title: "",
        type: type,
        required: false
      };
      
      // 根据类型初始化问题
      if (type === 'radio' || type === 'checkbox') {
        newQuestion.options = [
          { label: "选项1", value: "1" },
          { label: "选项2", value: "2" },
          { label: "选项3", value: "3" }
        ];
      } else if (type === 'text') {
        newQuestion.rows = 3;
        newQuestion.placeholder = "请输入您的答案";
      } else if (type === 'rate') {
        newQuestion.max = 5;
      }
      
      this.survey.questions.push(newQuestion);
      // 展开新添加的问题
      this.$nextTick(() => {
        this.activeNames = [this.survey.questions.length - 1];
      });
    },
    
    // 复制问题
    copyQuestion(index) {
      const question = JSON.parse(JSON.stringify(this.survey.questions[index]));
      question.title = question.title + " (复制)";
      this.survey.questions.splice(index + 1, 0, question);
      // 展开复制的问题
      this.$nextTick(() => {
        this.activeNames = [index + 1];
      });
    },
    
    // 删除问题
    removeQuestion(index) {
      this.$confirm('确定要删除此问题吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.survey.questions.splice(index, 1);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {});
    },
    
    // 添加选项
    addOption(questionIndex) {
      const question = this.survey.questions[questionIndex];
      const newOption = {
        label: `选项${question.options.length + 1}`,
        value: (question.options.length + 1).toString()
      };
      question.options.push(newOption);
    },
    
    // 删除选项
    removeOption(questionIndex, optionIndex) {
      const question = this.survey.questions[questionIndex];
      if (question.options.length <= 2) {
        this.$message.warning('至少需要保留两个选项');
        return;
      }
      question.options.splice(optionIndex, 1);
    },
    
    // 问题类型变更处理
    handleTypeChange(index) {
      const question = this.survey.questions[index];
      // 根据新类型重置问题属性
      if (question.type === 'radio' || question.type === 'checkbox') {
        if (!question.options) {
          question.options = [
            { label: "选项1", value: "1" },
            { label: "选项2", value: "2" },
            { label: "选项3", value: "3" }
          ];
        }
      } else if (question.type === 'text') {
        question.rows = 3;
        question.placeholder = "请输入您的答案";
      } else if (question.type === 'rate') {
        question.max = 5;
      }
    },
    
    // 使用模板
    useTemplate(template) {
      this.$confirm('使用模板将会替换当前所有问题，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.survey.questions = JSON.parse(JSON.stringify(template.questions));
        this.$message({
          type: 'success',
          message: '模板应用成功!'
        });
        // 展开第一个问题
        this.$nextTick(() => {
          this.activeNames = [0];
        });
      }).catch(() => {});
    },
    
    // 保存问卷
    saveSurvey() {
      // 表单验证
      if (!this.survey.title) {
        this.$message.error('请输入问卷标题');
        return;
      }
      
      if (this.survey.questions.length === 0) {
        this.$message.error('请至少添加一个问题');
        return;
      }
      
      // 检查每个问题是否有标题
      for (let i = 0; i < this.survey.questions.length; i++) {
        const question = this.survey.questions[i];
        if (!question.title) {
          this.$message.error(`第${i+1}个问题没有标题`);
          return;
        }
        
        // 检查选项类问题是否有选项
        if ((question.type === 'radio' || question.type === 'checkbox') && 
            (!question.options || question.options.length < 2)) {
          this.$message.error(`第${i+1}个问题选项数量不足`);
          return;
        }
      }
      
      // 这里应该调用后端接口保存问卷，暂时使用模拟数据
      this.$message.success('问卷保存成功');
    },
    
    // 发布问卷
    publishSurvey() {
      // 先保存问卷
      this.saveSurvey();
      
      // 确认发布
      this.$confirm('发布后问卷将可以被用户访问和填写，是否确认发布?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 这里应该调用后端接口发布问卷，暂时使用模拟数据
        this.survey.status = '1';
        this.$message({
          type: 'success',
          message: '问卷发布成功!'
        });
      }).catch(() => {});
    },
    
    // 预览问卷
    previewSurvey() {
      // 初始化预览答案
      this.resetPreview();
      this.previewVisible = true;
    },
    
    // 关闭预览
    closePreview() {
      this.previewVisible = false;
    },
    
    // 重置预览答案
    resetPreview() {
      this.previewAnswers = this.survey.questions.map(question => {
        if (question.type === 'checkbox') {
          return [];
        } else if (question.type === 'rate') {
          return 0;
        } else {
          return '';
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.survey-design {
  .edit-area {
    .survey-header {
      margin-bottom: 30px;
      
      .title-input {
        font-size: 18px;
        margin-bottom: 15px;
        
        :deep(.el-input__inner) {
          font-size: 18px;
          font-weight: bold;
        }
      }
      
      .desc-input {
        margin-bottom: 15px;
      }
      
      .survey-settings {
        background-color: #f8f9fa;
        border-radius: 4px;
        padding: 10px;
      }
    }
    
    .questions-container {
      margin-bottom: 20px;
      
      .question-header {
        display: flex;
        align-items: center;
        
        .drag-handle {
          cursor: move;
          margin-right: 8px;
          color: #909399;
        }
        
        .question-title {
          flex: 1;
          margin-right: 8px;
        }
        
        .question-type {
          color: #909399;
          margin-right: 8px;
        }
      }
      
      .question-edit {
        padding: 10px 0;
        
        .option-item {
          margin-bottom: 10px;
        }
        
        .add-option {
          margin-top: 10px;
        }
        
        .question-actions {
          margin-top: 15px;
          text-align: right;
          
          .el-button {
            margin-left: 15px;
          }
        }
      }
    }
    
    .add-question {
      margin: 20px 0;
      text-align: center;
    }
  }
  
  .settings-area {
    .template-list {
      .template-item {
        display: flex;
        align-items: center;
        padding: 15px;
        border-radius: 4px;
        margin-bottom: 15px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        .template-icon {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background-color: #ecf5ff;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 15px;
          
          i {
            font-size: 20px;
            color: #409EFF;
          }
        }
        
        .template-info {
          flex: 1;
          
          .template-title {
            font-weight: bold;
            margin-bottom: 5px;
          }
          
          .template-desc {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
}

.preview-container {
  .preview-header {
    text-align: center;
    margin-bottom: 30px;
    
    .preview-title {
      font-size: 20px;
      margin-bottom: 10px;
    }
    
    .preview-description {
      color: #606266;
    }
  }
  
  .preview-body {
    .preview-question {
      margin-bottom: 25px;
      
      .question-title {
        margin-bottom: 15px;
        
        .question-index {
          margin-right: 5px;
        }
        
        .question-required {
          color: #F56C6C;
          margin-left: 4px;
        }
      }
      
      .question-options {
        padding-left: 20px;
        
        .option-item {
          margin-bottom: 10px;
        }
      }
    }
  }
  
  .preview-footer {
    text-align: center;
    margin-top: 30px;
  }
}

// 深度选择器，修改内部样式
:deep(.el-collapse-item__header) {
  background-color: #f8f9fa;
}

:deep(.el-collapse-item.is-active .el-collapse-item__header) {
  color: #409EFF;
}
</style> 